package service

import (
	"context"
	"fmt"
	"golang.org/x/exp/rand"
	"shop_srvs/user_srv/service/repository"
	types "shop_srvs/user_srv/service/sms"
)

const codeTplId = "1877556"

type CodeService interface {
	Send(ctx context.Context, biz string, phone string) error
	Verify(ctx context.Context, biz string, phone string, inputCode string) error
}
type codeService struct {
	repo   *repository.CodeRepository
	smsSvc types.Service
}

func NewCodeService(repo *repository.CodeRepository, smsSvc types.Service) CodeService {
	return &codeService{
		repo:   repo,
		smsSvc: smsSvc,
	}
}
func (srv *codeService) Send(ctx context.Context,
	// 区别业务场景
	biz string,
	phone string) error {
	//生成验证码
	code := srv.generateCode()
	//塞进redis
	if err := srv.repo.Store(ctx, biz, phone, code); err != nil {
		return err
	}
	fmt.Println(code)
	//发送出去
	//err := srv.smsSvc.Send(ctx, codeTplId, []string{code}, phone)
	//if err != nil {
	//	//redis有验证码，你没发成功
	//	//可以重试
	//
	//}

	return nil
}

// 验证
func (srv *codeService) Verify(ctx context.Context, biz string, phone string,
	inputCode string) error {
	ok, err := srv.repo.Verify(ctx, biz, phone, inputCode)
	if !ok {
		return err
	}
	return nil
}

// 生成验证码
func (srv *codeService) generateCode() string {
	num := rand.Intn(1000000)
	return fmt.Sprintf("%06d", num)
}
